package apps.sim.http;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import apps.sim.action.handler.HandlerFactory;
import apps.sim.core.IHandler.IHandlerConfig;

import com.sun.net.httpserver.HttpExchange;

public class HttpDefaultHandler extends HttpBaseHandler {

	@Override
	protected void execute(HttpExchange exchange) throws Exception {
		final StringBuilder builder = new StringBuilder();
		BufferedReader bufferedReader = null;
		try {
			final File file = getShycopConfig();
			bufferedReader = new BufferedReader(new FileReader(file));

			String line;
			while ((line = bufferedReader.readLine()) != null) {
				builder.append(line);
			}
		} catch (FileNotFoundException fnfe) {

		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
		}
		final String string = builder.toString();
		initialize(string);
		successResponse(exchange, new ByteArrayInputStream(string.getBytes()), "text/xml;charset=utf-8");

	}

	private void initialize(String string) {
		int start = 0;
		while (string.indexOf("<handler>", start) != -1) {
			int index = string.indexOf("<handler>", start);
			if (index != -1) {
				start = string.indexOf("</handler>", index);
				if (start != -1) {
					int confIndex = string.indexOf("<configuration>", start);
					if (confIndex != -1) {
						try {
							final String handler = string.substring(index + 9, start);
							final String configutation = string.substring(confIndex + 15, string.indexOf("</configuration>", confIndex));
							final IHandlerConfig handlerConfiguration = HandlerFactory.getInstance().getRootHandler(handler.trim()).getHandlerConfiguration();
							if (handlerConfiguration != null && configutation != null) {
								handlerConfiguration.fromString(configutation);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}